package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void saveOrder(Order order) {
        User user = UserHolder.get();
        List<Cart> list = cartService.findList();
        if (CollectionUtil.isEmpty(list)) {
            throw new CustomException("购物车是空的!");
        }
        //4. 手动使用雪花算法生一个订单id
        Long orderId = IdWorker.getId();//mybatisplus工具类生成雪花算法的id

        BigDecimal total = new BigDecimal(0);//double total = 0
        //total += number * amount
        //5. 生成订单详情
        for (Cart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(orderId);//当前明细所属订单的id
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());

            //保存到数据表
            orderDetailMapper.insert(orderDetail);

            //每次遍历的时候添加金额
            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));//total += amount * number
        }
        Address address = addressMapper.selectById(order.getAddressId());

        if (address == null) {
            throw new CustomException("收货地址不存在,无法生成订单");
        }
        //6. 生成订单
        order.setId(orderId);//使用刚刚生成的orderid
        order.setNumber(orderId + "");//订单号 使用订单id
        order.setStatus(0);//待付款
        order.setUserId(user.getId());//登录用户id
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//支付时间(支付的时候再更新一下)
        order.setAmount(total);//本次订单总金额=所有明细中单价*数量再相加
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);

        //7. 清空当前用户购物车
        cartService.clean();
    }

    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {
        //准备分页对象
        Page<Order> page = new Page<>(pageNum, pageSize);
        //判断number是否为空
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(number),Order::getNumber,number);
        page = orderMapper.selectPage(page,wrapper);
        return page;
    }

    @Override
    public Page<Order> findHistoryOrders(Integer pageNum, Integer pageSize) {
        //准备分页对象
        Page<Order> page = new Page<>(pageNum, pageSize);
        //获取用户订单
        User user = UserHolder.get();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,user.getId());
        List<Order> orderList = orderMapper.selectList(wrapper);
        page = orderMapper.selectPage(page,wrapper);
        for (Order order : orderList) {
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
            order.setOrderDetails(orderDetails);
        }
        page.setRecords(orderList);


        return page;
    }
}
